/**
 * CORS 中间件
 * 处理跨域资源共享
 */
const corsMiddleware = async (ctx, next) => {
  // 设置允许的源
  const allowedOrigins = process.env.ALLOWED_ORIGINS 
    ? process.env.ALLOWED_ORIGINS.split(',')
    : ['http://localhost:3000', 'http://localhost:4200', 'http://localhost:5173', 'http://localhost:8080'];
  
  const origin = ctx.headers.origin;
  
  if (allowedOrigins.includes(origin)) {
    ctx.set('Access-Control-Allow-Origin', origin);
  }
  
  // 设置允许的方法
  ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
  
  // 设置允许的请求头
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  
  // 允许携带凭证
  ctx.set('Access-Control-Allow-Credentials', 'true');
  
  // 设置预检请求的缓存时间（秒）
  ctx.set('Access-Control-Max-Age', '86400'); // 24小时
  
  // 处理预检请求
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
    ctx.body = '';
    return;
  }
  
  await next();
};

module.exports = corsMiddleware;